package com.hlxj.license.server.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.File;
import java.util.Properties;

/**
 * @功能:【SendMailUtil 邮件发送工具类】
 * @作者:代守诚
 * @日期:2019/5/30
 * @时间:10:14
 */
public class SendMailUtil {
    private final static Logger logger = LogManager.getLogger(SendMailUtil.class);
    private static SendMailUtil sendMailUtil = null;

    //设置服务器
    private String ketSmpt;
    private String valueSmtp;
    //服务器验证
    private String keyProps;
    private boolean valueProps;
    //发件人用户名、密码
    private String sendUname;
    private String sendPwd;
    //建立会话
    private MimeMessage message;
    private Session session;

    private SendMailUtil(String keySmpt, String valueSmtp, String keyProps,
                         Integer valueProps, final String sendUname, final String sendPwd) {
        this.ketSmpt = keySmpt;
        this.valueSmtp = valueSmtp;
        this.keyProps = keyProps;
        this.valueProps = valueProps == 0;
        this.sendUname = sendUname;
        this.sendPwd = sendPwd;

        Properties properties = System.getProperties();
        properties.setProperty(keySmpt, valueSmtp);
        properties.put(keyProps, "false");
        session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(sendUname, sendPwd);
            }
        });

        message = new MimeMessage(session);
    }

    /**
     * 发送邮件
     * @param headName 邮件头文件名
     * @param sendHtml 邮件内容
     * @param receiveUser 收件人
     * @param attachment 文件
     */
    public void doSendHtmlEmail(String headName, String sendHtml, String receiveUser, File attachment) throws Exception{
        logger.info("******************收件人邮箱*******************" + receiveUser);
        //发件人
        String nickName = MimeUtility.encodeText("海隆行建");
        InternetAddress address = new InternetAddress(nickName + " <" + sendUname + ">");
        message.setFrom(address);

        //
        message.setRecipients(Message.RecipientType.BCC, "no-reply@17j.club");

        //收件人
        InternetAddress toAddress = new InternetAddress(receiveUser);
        message.setRecipient(Message.RecipientType.TO, toAddress);

        //邮件标题
        message.setSubject(headName);

        //向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
        Multipart multipart = new MimeMultipart();

        //添加邮件正文
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setContent(sendHtml, "text/html;charset=UTF-8");
        multipart.addBodyPart(bodyPart);

        //添加附件内容
        if(attachment != null) {
            BodyPart attachmentBodyPart = new MimeBodyPart();
            DataSource dataSource = new FileDataSource(attachment);
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));

            //网上流传的解决文件名乱码的方法，其实眼红MimeUtility.encodeWord就可以搞定
            // 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
            //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
            //messageBodyPart.setFileName("=?GBK?B?" + enc.encode(attachment.getName().getBytes()) + "?=");

            //MimeUtility.encodeWord可以避免文件名乱码
            attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
            multipart.addBodyPart(attachmentBodyPart);
        }
        message.setContent(multipart);

        Transport transport = session.getTransport("smtp");

        //发送
        //smtp验证，就是你用啦发邮件的邮箱用户名密码
        transport.connect(valueSmtp, sendUname, sendPwd);

        transport.sendMessage(message, message.getAllRecipients());
        transport.close();

    }

    /**
     * 发送邮件
     * @param mail
     * @param file
     * @param uuid
     * @param month
     * @throws Exception
     */
    public void sendMailFile(String mail, File file, String uuid, String month) throws Exception {
        String subject = "海隆行建RPA激活用户";

        StringBuffer sb = new StringBuffer();

        sb.append("<p class='p1' style='margin:1rem 0;font-size: 1.3rem;line-height: 2.5rem;color:#333;'>尊敬的RPA用户：");

        sb.append(mail);
        sb.append("</p>");
        sb.append("<p class='p2' style='margin:1rem 0 4rem;font-size: 1.3rem;line-height: 2.5rem;color:#333;'>您的激活码为：");
        sb.append(uuid);
        sb.append("</p>");
        sb.append("<p class='p2' style='margin:1rem 0 4rem;font-size: 1.3rem;line-height: 2.5rem;color:#333;'>您的激活年限为：");
        sb.append(month);
        sb.append("</p>");
        sb.append("<p class='p2' style='margin:1rem 0 4rem;font-size: 1.3rem;line-height: 2.5rem;color:#333;'>附件为您的公钥，请注意查收。</p>");
        sb.append("</p>");
        sb.append("<p class='p4' style='margin:1.3rem 0;color:#999;'>（此为系统邮件，请勿回复）</p>");

        doSendHtmlEmail(subject, sb.toString(), mail, file);
    }

    public static SendMailUtil getInstance() {
        if (sendMailUtil == null) {
            sendMailUtil = new SendMailUtil("mail.imap.host",
                    "mail.17j.club", "mail.imap.auth", 2,
                    "no-reply@17j.club", "zealFi@SHA8");
        }
        return sendMailUtil;
    }

    public static void main(String[] args) {
        try {
            String fileName = "publicKey";
            File file = new File(FileUtil.getBasePath() +  "\\" + fileName + ".txt");
            SendMailUtil.getInstance().sendMailFile("961658175@qq.com", file, "f17aaab091634eb997333dd7e2fb6b74", "6个月，到期时间为2020-01-01 15:55:44");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
